﻿using Microsoft.Xna.Framework;

namespace Ultima.Xna.Extensions
{
    public static class GameServiceContainerExtensions
    {
        /// <summary>
        /// Returns a service from the container of type T.  If no service is found default(T) will be returned.
        /// </summary>
        /// <typeparam name="T">The type of service to find in the service container</typeparam>
        public static T GetService<T>(this GameServiceContainer service)
        {
            return service.GetService<T>(false);
        }

        /// <summary>
        /// Returns a service from the container of type T.  If no service is found default(T) will be returned.
        /// </summary>
        /// <typeparam name="T">The type of service to find in the service container</typeparam>
        /// <typeparam name="throwExceptionIfNotFound">If no service of type T is found and throwExceptionIfNotFound is true, an exception will be thrown.</typeparam>
        public static T GetService<T>(this GameServiceContainer service, bool throwExceptionIfNotFound)
        {
            object o = service.GetService(typeof(T));

            if (o is T)
            {
                return (T)o;
            }
            else if(throwExceptionIfNotFound)
            {
                throw new ServiceNotFoundException(typeof(T).Name);
            }

            return default(T);
        }

        /// <summary>
        /// Adds a service of type T to the container
        /// </summary>
        public static void AddService<T>(this GameServiceContainer service, T item)
        {
            service.AddService(typeof(T), item);
        }
    }
}
